// 文章接口
var express = require('express');
var router = express.Router();
const sql = require('../conf/sql.js')
const pool = require('../conf/db.js')

// 获取病人列表
router.get('/patient_list', (req, res, next) => {
  let { uid } = req.query
  pool.query(sql.patient_list, [uid], (err, result) => {
    if (err) {
      next(err)
      return
    }
    if (result.length == 0) {
      res.json({
        code: 201,
        msg: 'failed',
      })
    } else {
      res.json({
        code: 200,
        msg: 'get patient_list success',
        data: result
      })
    }
    
  })
})

// 获取单个病人信息
router.get('/single_detail', (req, res, next) => {
  let { id } = req.query
  pool.query(sql.single_detail, [id], (err, result) => {
    if (err) {
      next(err)
      return
    }
    if (result.length == 0) {
      res.json({
        code: 201,
        msg: 'failed',
      })
    } else {
      res.json({
        code: 200,
        msg: 'get single_detail success',
        data: result[0]
      })
    }
    
  })
})
// 添加新病人
router.post('/add_patient', (req, res, next) => {
  // uid是当前登录用户的id，存储在vuex中
  let { name, id_number, patient_number, address, phone, uid, relation } = req.body
  // 查找表中是否已存在该病人
  let selectname = 'select count(id) as count from patient where name = ?'
  pool.query(selectname, [name], (err, result) => {
    if (err) {
      next(err)
      return
    }
    let count = result[0].count
    if (count == 0) {
      pool.query(sql.add_patient, [req.body], (err, result) => {
        if (err) {
          next(err)
          return
        }
        res.json({
          code: 200,
          msg: '新增病人成功'
        })
      })
    } else {
      res.json({
        code: 201,
        msg: '病人已存在'
      })
    }
  })
})













// 用户选择日期进行预约操作,若预约成功，此时需要将hospital里的疫苗库存减1
router.get('/add_patient', function (req, res, next) {
  pool.query(sql.add_patient, (err, result) => {
    if (err) {
      next(err)
      return
    }
    // console.log(result);
    if (result.length == 0) {
      res.json({
        code: 201,
        msg: 'failed',
      })
    } else {
      res.json({
        code: 200,
        msg: 'get hospitallist success',
        data: result
      })
    }

  })

});

module.exports = router;
